<?php


namespace App\Http\Controllers\Admin\Critical;


use App\Enums\CriticalEnum;
use App\Enums\RedisKeyEnum;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use App\Services\Tools\HelperService;
use App\Traits\AdminLog;
use Illuminate\Http\Request;
use Symfony\Component\Console\Helper\Helper;

//暴击奖池配置奖品
class CriticalPrizeController extends BaseController
{
    use AdminLog;
    private $moduleId = CriticalEnum::MODULE_TREE;
    /**
     * @api {put} /critical/gift 暴击礼物新增/编辑
     *
     * @apiGroup  暴击奖池
     *
     * @apiParam {int} gift_id 目标礼物id 必传
     * @apiParam {Int} old_gift_id 编辑的原礼物id
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[],"msg":"设置成功"}
     *
     */
    public function set(Request $request)
    {
        $param = $request->only('gift_id','old_gift_id');
        $v = app('validator')->make($param, [
            'gift_id' => 'required|integer|min:0',
        ]);
        if ($v->fails()){
            throw new BasicException(0, $v->errors()->first());
        }
        $giftId = $param['gift_id'];
        $oldGiftId = $param['old_gift_id']??0;
        $giftInfo = app('model_gift')->where([
            'id' =>$giftId,
            'is_delete' =>0,
        ])->first();
        if(empty($giftInfo)){
            throw new BasicException(0, '礼物不存在');
        }
        if(!empty($oldGiftId) && $oldGiftId == $giftId ){
            return Response::sendData([],'设置成功');
        }

        $poolGiftConfig = app('model_critical_prize')->where([
            'module' => $this->moduleId,
            'status' => 1,
        ])->get();
        $poolGiftConfig = empty($poolGiftConfig)?[]:$poolGiftConfig->toArray();
        $poolGift = [];
        $hasGift = app('model_critical_prize')->where([
            'module' => $this->moduleId,
            'gift_id' => $giftId,
            'status' => 3,
        ])->first();
        $hasGift = empty($hasGift)?[]:$hasGift->toArray();
        if(empty($oldGiftId)){ //新增
            if(count($poolGiftConfig)>=CriticalEnum::MODULE_TREE_MAX_GIFT_NUM){
                throw new BasicException(0, '最大支持'.CriticalEnum::MODULE_TREE_MAX_GIFT_NUM.'个奖品配置');
            }
            foreach ($poolGiftConfig as $v){
                if($v['gift_id'] == $giftId){
                    throw new BasicException(0, "奖品已在可抽列表,无需添加");
                }
            }
        }else{
            foreach ($poolGiftConfig as $v){
                if($v['gift_id'] == $oldGiftId){
                    $poolGift = $v;
                }
                if($v['gift_id'] == $giftId){
                    throw new BasicException(0, "编辑失败,当前添加的礼物已在可抽取列表内");
                }
            }
            if(empty($poolGift)){
                throw new BasicException(0, "编辑失败,原礼物不在可抽取列表");
            }
        }
        $data = [
            'module' => $this->moduleId,
            'gift_id' => $giftId,
            'status' => 1,
        ];
        if(empty($hasGift)){
            app('model_critical_prize')->insert($data);
        }else{
            app('model_critical_prize')->where([
                'id' => $hasGift['id']
            ])->update($data);
        }
        if(!empty($poolGift)){
            app('model_critical_prize')->where([
                'id' => $poolGift['id']
            ])->update([
                'status' => 3
            ]);
        }
        $key = (RedisKeyEnum::CRITICAL_GIFTS).$this->moduleId;
        app('redis')->del($key);
        return Response::sendData([],'设置成功');

    }


    /**
     * @api {delete} /critical/gift 删除暴击礼物
     *
     * @apiGroup  暴击奖池
     *
     * @apiParam {int} gift_id 礼物id
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[],"msg":"删除成功"}
     */
    public function del(Request $request)
    {
        $param = $request->only('gift_id','old_gift_id');
        $v = app('validator')->make($param, [
            'gift_id' => 'required|integer|min:0',
        ]);
        if ($v->fails()){
            throw new BasicException(0, $v->errors()->first());
        }
        $giftId = $param['gift_id'];
        $poolGiftConfig = app('model_critical_prize')->where([
            'gift_id' => $giftId,
            'module' =>$this->moduleId,
            'status' => 1
        ])->first();
        $poolGiftConfig = empty($poolGiftConfig)?[]:$poolGiftConfig->toArray();
        if(empty($poolGiftConfig)){
            throw new BasicException(0, '删除失败,礼物不在奖池内');
        }
        app('model_critical_prize')->where([
            'id' => $poolGiftConfig['id']
        ])->update([
            'status' => 3
        ]);
        $key = (RedisKeyEnum::CRITICAL_GIFTS).$this->moduleId;
        app('redis')->del($key);
        return Response::sendData([],'删除成功');
    }

    /**
     * @api {get} /critical/gift 暴击奖池详情
     * @apiGroup  暴击奖池
     *
     * @apiSuccessExample {json} Response-Example
     *{
    "code": 200,
    "data": {
    "list": [
    {
    "id": 1,
    "module": 1,
    "gift_id 礼物id": 542,
    "winner_num": 0,
    "winner_times": 0,
    "status": 1,
    "created_at": "2021-10-20 10:47:50",
    "updated_at": "2021-10-20 10:47:50",
    "winner_num_pool 当前奖池中奖个数(取这个字段)": 0,
    "winner_times_pool 当前奖池中奖次数": 0,
    "name 名称": "巫师帽",
    "price 价格": 1000,
    "picture 图片": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/newadmin/452a248f70c245ca1da666dd5607f139WpjAs.png"
    },
    {
    "id": 7,
    "module": 1,
    "gift_id": 546,
    "winner_num": 0,
    "winner_times": 0,
    "status": 1,
    "created_at": "2021-10-21 21:23:52",
    "updated_at": "2021-10-21 21:23:52",
    "winner_num_pool": 0,
    "winner_times_pool": 0,
    "name": "精灵的祝福",
    "price": 131400,
    "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/611b30765b200.png"
    }
    ],
    "level_coin_num 剩余奖池价值(取他)": 0,
    "redis_level_coin_num 缓存剩余奖池价值(忽略)": "7200"
    },
    "message": ""
    }
     */
    public function all(Request $request)
    {
        $list = app('model_critical_prize')->where([
            'module' => $this->moduleId,
            'status' =>1
        ])->get();
        $list = empty($list)?[]:$list->toArray();
        $levelCoinNum = app('model_critical_pool_coin_level')->where('module',$this->moduleId)->where('pool_type',CriticalEnum::TREE_COMMON_POOL)->where('user_id',0)->first(['level_coin_num']);
        $levelCoinNum = empty($levelCoinNum)?0:$levelCoinNum['level_coin_num'];
        $coinMoneyKey = "critical:level:coin:num:".$this->moduleId.":".CriticalEnum::TREE_COMMON_POOL.":0";//剩余的金币数
        $redisLevelCoinNum = app('redis')->get($coinMoneyKey);

        $poolPrizeList = app('model_critical_pool_prize')->where('module',$this->moduleId)->where('pool_type',CriticalEnum::TREE_COMMON_POOL)->where('user_id',0)->get();
        $poolPrizeList = empty($poolPrizeList)?[]:$poolPrizeList->toArray();
        $poolPrizeList = HelperService::indexToAssoc($poolPrizeList,'gift_id');
        $giftIds = HelperService::getArrayColumn($list,'gift_id');
        if(!empty($giftIds)){
            $gifts = app('model_gift')->whereIn('id',$giftIds)->get(['id','name','price','picture']);
            $gifts = empty($gifts)?[]:$gifts->toArray();
            $gifts = HelperService::indexToAssoc($gifts,'id');
        }else{
            $gifts = [];
        }

        foreach ($list as $k=>$v){
            $list[$k]['winner_num_pool'] = isset($poolPrizeList[$v['gift_id']])?$poolPrizeList[$v['gift_id']]['winner_num']:0;
            $list[$k]['winner_times_pool'] = isset($poolPrizeList[$v['gift_id']])?$poolPrizeList[$v['gift_id']]['winner_times']:0;
            $list[$k]['name'] = isset($gifts[$v['gift_id']])?$gifts[$v['gift_id']]['name']:'';
            $list[$k]['price'] = isset($gifts[$v['gift_id']])?$gifts[$v['gift_id']]['price']:'';
            $list[$k]['price'] = isset($gifts[$v['gift_id']])?$gifts[$v['gift_id']]['price']:0;
            $list[$k]['picture'] = isset($gifts[$v['gift_id']])?$gifts[$v['gift_id']]['picture']:'';
        }
        return Response::sendData([
            'list' => $list,
            'level_coin_num' => $levelCoinNum,
            'redis_level_coin_num' => (int)($redisLevelCoinNum??0),
        ]);
    }
}